package com.kang.user.controller;

import com.kang.common.R;
import com.kang.user.client.ManagerClient;
import com.kang.user.entity.User;
import com.kang.user.service.IUserService;
import com.kang.user.to.BrandTo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 用户控制器
 * 提供用户相关接口和与品牌相关的功能接口。
 */
@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {

	@Autowired
	private IUserService userService;

	@Autowired
	private ManagerClient client;

	@Autowired
	private HttpServletRequest request;

	@Autowired
	private HttpServletResponse response;

	/**
	 * 获取用户列表
	 *
	 * @return 包含用户列表的响应对象
	 */
	@GetMapping("/list")
	public R list() {
		log.info("Fetching user list.");
		return R.ok().put("list", userService.list());
	}

	/**
	 * 保存用户
	 *
	 * @param user 用户实体
	 * @return 保存操作结果
	 */
	@PostMapping("/save")
	public R save(@RequestBody User user) {
		log.info("Saving user: {}", user);
		userService.save(user);
		return R.ok();
	}

	/**
	 * 获取请求头和参数信息
	 *
	 * @return 包含请求头和参数信息的响应对象
	 */
	@GetMapping("/info")
	public R info() {
		String header = request.getHeader("h-01");
		String color = request.getParameter("color");
		String welcomeHeader = request.getHeader("welcome-header");

		log.info("Received headers - h-01: {}, welcome-header: {}, color: {}", header, welcomeHeader, color);

		return R.ok()
				.put("header", header)
				.put("welcomeHeader", welcomeHeader)
				.put("color", color);
	}

	/**
	 * 查询品牌列表
	 *
	 * @return 包含品牌列表的响应对象
	 */
	@GetMapping("/brand/list")
	public R findBrandList() {
		String username = request.getHeader("username");
		log.info("Fetching brand list for username: {}", username);

		String cookieValue = "2025-1-14日创建cookie";
		response.addCookie(new Cookie("c1", cookieValue));

		return client.findAll(cookieValue);
	}

	/**
	 * 根据 ID 查询单个品牌
	 *
	 * @param id 品牌 ID
	 * @return 品牌信息
	 */
	@GetMapping("/brand/findById/{id}")
	public R findById(@PathVariable Long id) {
		log.info("Fetching brand by ID: {}", id);
		return client.findById(id);
	}

	/**
	 * 保存品牌
	 *
	 * @param to 品牌传输对象
	 * @return 保存操作结果
	 */
	@PostMapping("/brand/save")
	public R saveBrand(@RequestBody BrandTo to) {
		log.info("Saving brand: {}", to);
		return client.add(to);
	}
}
